#include "ls.h"
int Sendls(int peerfd, char *pathname){
    if(strlen(pathname) == 0){
        strcpy(pathname, "./");
    }
    DIR *pdir = opendir(pathname);
    if(pdir == NULL){
        char errmsg[1024] = {0};
        sprintf(errmsg, "%s\n", strerror(errno));
        train_t train;
        train.len = strlen(errmsg);
        strcpy(train.data, errmsg);
        send(peerfd, &train, 4 + train.len, MSG_WAITALL);
        printf("err:%s", train.data);
        return -1;
    }
    //ERROR_CHECK(pdir, NULL, "opendir");
    struct stat statbuf;
    struct dirent *pdirent;
    errno = 0;
    char sendbuf[1024] = {0};
    while((pdirent = readdir(pdir)) != NULL){
        if(pdirent->d_name[0] == '.'){
            continue;
        }
        if(pdirent->d_type == DT_DIR){
            char path[1024];
            sprintf(path, "%s/%s", pathname, pdirent->d_name);
                    int retval = stat(path, &statbuf);
            //ERROR_CHECK(retval, -1, "stat");
            struct tm* ptime = localtime(&statbuf.st_atime);
            //ERROR_CHECK(ptime, NULL, "localtime");
            char dmsg[1024] = {0};
            sprintf(dmsg, BLUE "%-15s/ %15ld %d/%.2d/%.2d %.2d:%.2d:%.2d \n",
                    pdirent->d_name, statbuf.st_size,
                    ptime->tm_year + 1900,
                    ptime->tm_mon + 1,
                    ptime->tm_mday,
                    ptime->tm_hour,
                    ptime->tm_min,
                    ptime->tm_sec);
            strcat(sendbuf, dmsg);
            //send(peerfd, sendbuf, strlen(sendbuf), MSG_WAITALL);
        }
    }
    closedir(pdir);
    pdir = opendir(pathname);
    while((pdirent = readdir(pdir)) != NULL){
        if(pdirent->d_name[0] == '.'){
            continue;
        }
        if(pdirent->d_type == DT_REG){
            char path[1024];
            sprintf(path, "%s/%s", pathname, pdirent->d_name);
            int retval = stat(path, &statbuf);
            ERROR_CHECK(retval, -1, "stat");
            struct tm* ptime = localtime(&statbuf.st_atime);
            ERROR_CHECK(ptime, NULL, "localtime");
            char rmsg[1024] = {0};
            sprintf(rmsg, NONE "%-15s %15ld %d/%.2d/%.2d %.2d:%.2d:%.2d \n",
                    pdirent->d_name, statbuf.st_size,
                    ptime->tm_year + 1900,
                    ptime->tm_mon + 1,
                    ptime->tm_mday,
                    ptime->tm_hour,
                    ptime->tm_min,
                    ptime->tm_sec);
            strcat(sendbuf, rmsg);
            //send(peerfd, sendbuf, strlen(sendbuf), MSG_WAITALL);
        }
    }
    train_t train;
    train.len = strlen(sendbuf);
    strcpy(train.data, sendbuf);
    send(peerfd, &train, 4 + train.len, MSG_WAITALL);
    closedir(pdir);
    printf("end:%s", train.data);
    return 0;
}
